<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="项目标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入项目标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="申请时间" prop="applyDate">
        <el-date-picker
          clearable
          v-model="queryParams.applyDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间"
        >
        </el-date-picker>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="projectsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="项目ID" align="center" prop="id" />
      <el-table-column label="申请人" align="center" prop="applicantName" />
      <el-table-column label="项目标题" align="center" prop="title" />
      <el-table-column label="项目描述" align="center" prop="description" />
      <el-table-column
        label="申请时间"
        align="center"
        prop="applyDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="startDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="交付时间"
        align="center"
        prop="deadline"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.deadline, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="status" />
      <el-table-column label="项目预算金额" align="center" prop="budget" />
      <el-table-column
        label="研究计划"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-link
            type="primary"
            href="javascript:;"
            @click="handleView(scope.row)"
            >查看研究计划</el-link
          >
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              link
              @click="showReason(row)"
              v-if="row.status === '驳回'"
              >查看原因</el-button
            >
            <el-button
              type="primary"
              link
              @click="submitProject(row)"
              :disabled="row.status !== '评审中'"
              >通过</el-button
            >
            <el-button
              :disabled="row.status !== '评审中'"
              type="danger"
              link
              @click="rejectProject(row)"
              >不通过</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目基本信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="projectsRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="项目标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入项目标题" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="项目申请书文件路径" prop="applicationFile">
          <file-upload v-model="form.applicationFile" />
        </el-form-item>
        <el-form-item label="论证报告文件路径" prop="demonstrationFile">
          <file-upload v-model="form.demonstrationFile" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applyDate">
          <el-date-picker
            clearable
            v-model="form.applyDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目开始日期" prop="startDate">
          <el-date-picker
            clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择项目开始日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目截止日期" prop="deadline">
          <el-date-picker
            clearable
            v-model="form.deadline"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择项目截止日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目预算金额" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入项目预算金额" />
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker
            clearable
            v-model="form.createdAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录更新时间" prop="updatedAt">
          <el-date-picker
            clearable
            v-model="form.updatedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录更新时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Word文档查看对话框 -->
    <el-dialog
      title="研究计划文档"
      v-model="docDialogVisible"
      width="80%"
      append-to-body
      destroy-on-close
    >
      <div class="w-full overflow-auto">
        <vue-office-docx
          v-if="previewType === 'docx' || previewType === 'doc'"
          :src="src"
        />
        <vue-office-pdf v-if="previewType === 'pdf'" :src="src" />
      </div>
    </el-dialog>

    <!-- 查看不通过对话框 -->
    <el-dialog v-model="showReasonDialog" title="不通过原因" width="800px">
      <!-- <el-table :data="commentsList" style="width: 100%">
          <el-table-column  label="审核意见" />
        </el-table> -->

      <div v-for="item in reasonList" :key="item" class="text item">
        {{ item }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Projects">
import {
  listProjects,
  getProjects,
  delProjects,
  addProjects,
  updateProjects,
} from "@/api/project/application.js"

import { pass, reject, getReason } from "@/api/project/review.js"
import VueOfficeDocx from "@vue-office/docx"
import VueOfficePdf from "@vue-office/pdf"

const src = ref("")
const docDialogVisible = ref(false)

const { proxy } = getCurrentInstance()

const projectsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const showReasonDialog = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicantId: null,
    title: null,
    description: null,
    applicationFile: null,
    demonstrationFile: null,
    applyDate: null,
    status: null,
    startDate: null,
    deadline: null,
    budget: null,
    createdAt: null,
    updatedAt: null,
  },
  rules: {
    applicantId: [
      { required: true, message: "申请人ID不能为空", trigger: "blur" },
    ],
    title: [{ required: true, message: "项目标题不能为空", trigger: "blur" }],
    applyDate: [
      { required: true, message: "申请时间不能为空", trigger: "blur" },
    ],
    status: [
      { required: true, message: "项目状态不能为空", trigger: "change" },
    ],
    createdAt: [
      { required: true, message: "记录创建时间不能为空", trigger: "blur" },
    ],
    updatedAt: [
      { required: true, message: "记录更新时间不能为空", trigger: "blur" },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询项目基本信息列表 */
function getList() {
  loading.value = true
  listProjects(queryParams.value).then((response) => {
    projectsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

const submitProject = (row) => {
  pass({ projectId: row.id }).then((response) => {
    proxy.$modal.msgSuccess("通过成功")
    getList()
  })
}

// 不通过时，弹出原因框
const rejectProject = (row) => {
  proxy.$modal
    .prompt("请输入不通过原因", "不通过原因", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: "",
    })
    .then(({ value }) => {
      if (value) {
        // 调用不通过接口
        reject({ projectId: row.id, reason: value }).then((response) => {
          proxy.$modal.msgSuccess("不通过成功")
          getList()
        })
      }
    })
}

const reasonList = ref([])
const showReason = (row) => {
  debugger

  getReason({ projectId: row.id }).then((response) => {
    if (!response.rows) {
      proxy.$modal.msgError("该项目没有不通过原因")
    }
    showReasonDialog.value = true
    // 根据后端返回的数据，TODO
    const data = response.rows
    reasonList.value = data.map((item) => item.comments)
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    applicantId: null,
    title: null,
    description: null,
    applicationFile: null,
    demonstrationFile: null,
    applyDate: null,
    status: null,
    startDate: null,
    deadline: null,
    budget: null,
    createdAt: null,
    updatedAt: null,
  }
  proxy.resetForm("projectsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

const previewType = ref("")
const getFileExtension = (filename) => {
  return filename
    .slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2)
    .toLowerCase()
}
function handleView(row) {
  const url = `http://localhost:8080${row.applicationFile}`
  if (url) {
    fetch(url)
      .then((response) => {
        if (!response.ok) throw new Error("Network response was not ok")
        previewType.value = getFileExtension(row.applicationFile)
        return response.arrayBuffer()
      })
      .then((arrayBuffer) => {
        src.value = arrayBuffer // 将文件内容赋值给src，vue-office-docx组件会自动渲染
        docDialogVisible.value = true // 显示文档对话框
      })
      .catch((error) => {
        console.error("Failed to fetch the document:", error)
      })
  }
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectsRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateProjects(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProjects(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

getList()
</script>
